import permision from "@/js_sdk/wa-permission/permission.js"
const recorderManager = uni.getRecorderManager();

let isIos
// #ifdef APP-PLUS
isIos = (plus.os.name == "iOS")
// #endif

// ios
const judgeIosPermission = async (permisionID, content) => {
	const result = await permision.judgeIosPermission(permisionID)
	console.log("ios权限状态---", result)

	// 相册、相机权限：0-未发起过授权；2-发起过，拒绝授权；3-已授权

	//位置权限： 0-下次询问或在我共享时；4-使用app期间允许授权

	// 麦克风权限：1970168948-未发起过授权；1735552628-已授权；1684369017-发起过，拒绝授权


	// 针对相机和相册，当未发起过授权，返回1，让对应页面去调一次API触发授权框弹出
	if ((permisionID == "photoLibrary" || permisionID == "camera") && result == 0) {
		return 1
	}

	// 针对位置
	if (permisionID == "location" && (result == 0 || result == 4)) {
		return 1
	}

	// 针对麦克风，当未发起过授权，主动调一下录音，让对应页面去调一次API触发授权框弹出
	if (permisionID == "record" && result == 1970168948) {
		// 开始录音
		recorderManager.start();
		setTimeout(() => {
			recorderManager.stop();
		}, 500)
		return 197
	}

	if (result == 3 || result == 1735552628) return 1

	if (result == 2 || result == 1684369017) {
		// uni.showModal({
		// 	content,
		// 	cancelText: "我知道了",
		// 	confirmText: "前往设置",
		// 	success: res => {
		// 		if (res.confirm) {
		// 			gotoAppPermissionSetting()
		// 		}
		// 	}
		// });
		return result
	}
	return result
}

// android 
const handleRequestAndroidPermission = async (params) => {
	let {
		permisionID
	} = params;
	const result = await permision.requestAndroidPermission(permisionID)
	// console.log("安卓权限状态---", result)

	// let strStatus
	if (result == 1) {
		// strStatus = "已获得授权"
		return result
	} else if (result == 0) {
		// strStatus = "未获得授权"
		return result
	} else {

		// strStatus = "被永久拒绝权限";
		uni.showModal({
			title: "温馨提示",
			content: "权限已被永久拒绝，无法获取，请前往设置页手动打开授权。",
			confirmText: "前往设置",
			cancelText: "我知道了",
			success: (res) => {
				if (res.confirm) {
					gotoAppPermissionSetting()
				}
			}
		});
		return result
	}
}

// 打开设置页面
export const gotoAppPermissionSetting = () => {
	permision.gotoAppPermissionSetting()
}

/**
 * 二次封装，统一处理ios/android
 * @param {String} permisionID 权限id
 */
export const requestPermission = (permisionID) => {
	return new Promise(async (resolve, reject) => {
		// #ifdef APP-PLUS
		if (isIos) {
			switch (permisionID) {
				case 'photoLibrary': // 相册权限，ios-相册权限
					resolve(judgeIosPermission("photoLibrary",
						"该应用需要读取你的相册，以便设置头像、发布动态/圈子或发送图片。"))
					break;

				case 'camera': // 摄像头权限
					resolve(judgeIosPermission("camera", "该应用需要你的相机，以便设置头像、发布动态/圈子或发送图片。"))
					break;

				case "location": // 位置权限
					resolve(judgeIosPermission("location", "该应用需要你的位置，以便为你提供附近好物推荐、动态或切换位置。"))
					break;

				case "microphone": // 麦克风权限
					resolve(judgeIosPermission("record", "该应用需要你的麦克风，以便发布动态/圈子时视频录制、语音录制。"))
					break;

				default:
					uni.showToast({
						title: "权限key错误",
						icon: "none"
					})
					break;
			}
			return
		}

		switch (permisionID) {
			case 'photoLibrary': // 相册权限，android-外部存储(含相册)读取权限

				let PHOTOID = "android.permission.READ_EXTERNAL_STORAGE";

				// android系统13以上。高版本安卓照片和视频权限需要分开授权。
				// 测试发现，只获取READ_MEDIA_VIDEO权限，也能拿到相册权限，原因未知。但只拿READ_MEDIA_IMAGES权限，一定无法拿到视频权限。
				if (plus.os.version >= 13) {
					PHOTOID = "android.permission.READ_MEDIA_VIDEO";
				}

				const _checkSTORAGE = await checkAndroidPermission(PHOTOID);
				if (_checkSTORAGE) {
					const result_PHOTOID = await handleRequestAndroidPermission({
						permisionID: PHOTOID
					})
					resolve(result_PHOTOID);
				} else {
					uni.showModal({
						title: "温馨提示",
						content: "该应用需要读取你的相册，以便设置头像、发布动态/圈子或发送图片。",
						cancelText: "稍后授权",
						confirmText: "去授权",
						success: async (res) => {
							if (res.confirm) {
								const result = await handleRequestAndroidPermission({
									permisionID: PHOTOID
								})
								resolve(result)
							}
						}
					})
				}

				break;

			case 'camera': // 摄像头权限
				const CAMERAID = "android.permission.CAMERA";
				const _checkCAMERA = await checkAndroidPermission(CAMERAID);
				if (_checkCAMERA) {
					const result_CAMERAID = await handleRequestAndroidPermission({
						permisionID: CAMERAID
					})
					resolve(result_CAMERAID)
				} else {
					uni.showModal({
						title: "温馨提示",
						content: "该应用需要你的相机，以便设置头像、发布动态/圈子或发送图片。",
						cancelText: "稍后授权",
						confirmText: "去授权",
						success: async (res) => {
							if (res.confirm) {
								const result = await handleRequestAndroidPermission({
									permisionID: CAMERAID
								})
								resolve(result)
							}
						}
					})
				}
				break;

			case "location": // 位置权限
				const LOCATIONID = "android.permission.ACCESS_FINE_LOCATION";
				const _checkLOCATION = await checkAndroidPermission(LOCATIONID);
				if (_checkLOCATION) {
					const result_LOCATIONID = await handleRequestAndroidPermission({
						permisionID: LOCATIONID
					})
					resolve(result_LOCATIONID)
				} else {
					uni.showModal({
						title: "温馨提示",
						content: "该应用需要你的位置，以便为你提供附近好物推荐、动态或切换位置。",
						cancelText: "稍后授权",
						confirmText: "去授权",
						success: async (res) => {
							if (res.confirm) {
								const result = await handleRequestAndroidPermission({
									permisionID: LOCATIONID
								})
								resolve(result)
							}
							if (res.cancel) {
								reject()
							}
						}
					})
				}
				break;

			case "microphone": // 麦克风权限
				const AUDIOID = "android.permission.RECORD_AUDIO";
				const _checkAUDIO = await checkAndroidPermission(AUDIOID);
				if (_checkAUDIO) {
					const result_AUDIOID = await handleRequestAndroidPermission({
						permisionID: AUDIOID
					})
					resolve(result_AUDIOID)
				} else {
					return await uni.showModal({
						title: "温馨提示",
						content: "该应用需要你的麦克风，以便发布动态/圈子时视频录制、语音录制。",
						cancelText: "稍后授权",
						confirmText: "去授权",
						success: async (res) => {
							if (res.confirm) {
								const result = await handleRequestAndroidPermission({
									permisionID: AUDIOID
								})
								resolve(result)
							}
						}
					})
				}
				break;

			case "callPhone": // 拨打电话权限
				const CALLPHONE = "android.permission.CALL_PHONE";
				const _check_CALLPHONE = await checkAndroidPermission(CALLPHONE);
				if (_check_CALLPHONE) {
					const result_CALLPHONE = await handleRequestAndroidPermission({
						permisionID: CALLPHONE
					})
					resolve(result_CALLPHONE)
				} else {
					return await uni.showModal({
						title: "温馨提示",
						content: "该应用需要你的电话权限，以便联系我们。",
						cancelText: "稍后授权",
						confirmText: "去授权",
						success: async (res) => {
							if (res.confirm) {
								const result = await handleRequestAndroidPermission({
									permisionID: CALLPHONE
								})
								resolve(result)
							}
						}
					})
				}
				break;

			default:
				uni.showToast({
					title: "权限key错误",
					icon: "none"
				})
				break;
		}
		// #endif

		// #ifdef H5 || MP-WEIXIN
		console.log('权限 H5 MP-WEIXIN')
		resolve(1)
		// #endif
	})
}

export const checkAndroidPermission = (permissionID) => {
	return new Promise((resolve) => {
		// #ifdef APP-PLUS
		if (isIos) {
			resolve(true)
			return
		}
		plus.android.checkPermission(permissionID,
			granted => {
				console.log("checkPermission--", permissionID, "---", granted)
				// -1-未授权；0-已授权
				if (granted.checkResult == -1) {
					resolve(false)
					return
				}
				resolve(true)
			},
			error => {
				resolve(false)
				console.log("checkAndroidPermission error---", error.message);
			}
		);
		// #endif

		// #ifdef H5 || MP-WEIXIN
		console.log('权限 H5 MP-WEIXIN')
		resolve(true)
		// #endif
	})
}